(function(){
  
var User = window.User || {};

User.Settings = (function(){
  
  var $email = $('#user-email');
  var $website = $('#user-website');
  
  var emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
  var urlRegex = /https?:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  
  var _initHandler = function() {
    $('#user-thumb').change(function(){
      var $t = $(this);
      var file = $t.get(0).files[0];
      
      if (!/image\/.*/.test(file.type)) {
        alert('您並未選擇合適的圖檔，請選擇 jpg 或是 png 檔案');
        return false;
      }
      
      // 即時顯示圖片
      var fr = new FileReader();
      fr.onload = function(evt) {
        $('#user-avatar').attr('src', evt.target.result);
      };
      fr.readAsDataURL(file);
    });
    
    $('#user-settings-form').submit(function(e){
      try {
        var emailVal = $email.val().trim();
        
        if (emailVal.length == 0) {
          throw {msg: '請填寫 email', obj: $email};
        }
        
        if (!emailRegex.test(emailVal)) {
          throw {msg: 'email 格式不正確', obj: $email};
        }
        
        var websiteVal = $website.val().trim();
        if (websiteVal.length > 0) {
          if (!urlRegex.test(websiteVal)) {
            throw {msg: 'Website 格式不正確', obj: $website}
          }
        }
        
      } catch (e) {
        alert(e.msg);
        e.obj.focus();
        return false;
      }
    });
  };
  
  return {
    init: function() {
      _initHandler();
    }
  };
  
})();

User.Settings.init();
  
})();
